package com.tt.aile.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tt.aile.common.pojo.PageResult;
import com.tt.aile.item.mapper.*;
import com.tt.aile.item.pojo.*;
import com.tt.aile.item.pojo.bo.SpuBo;
import org.apache.commons.lang.StringUtils;
import org.omg.PortableInterceptor.SUCCESSFUL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Transient;
import javax.script.ScriptEngine;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86176 shkstrat
 * @date 2020/10/6 - 16:38
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    public PageResult<SpuBo> querySpuBoByPage(String key, Boolean saleable, Integer page, Integer rows) {

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //1 添加模糊查询
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }

        //判断上下架
        if(saleable!=null){

            criteria.andEqualTo("saleable",saleable);
        }


        PageHelper.startPage(page,rows);

        // 执行查询
        List<Spu> spus = this.spuMapper.selectByExample(example);


        //新建一个分页类，助于分页
        PageInfo<Spu> pageInfo = new PageInfo<Spu>(spus);


//        System.out.println(pageInfo.getTotal()+"-------------------");
        //spu转化为spuBo
        List<SpuBo> spuBos = spus.stream().map(spu -> {

            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);

            spuBo.setBname(this.brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());
            List<String> categoryNames = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(categoryNames, "/"));

            return spuBo;
        }).collect(Collectors.toList());

        //System.out.println(spuBos.size()+"=----------------------------");
        return new PageResult<>(pageInfo.getTotal(),spuBos);


    }

    //新增商品
    @Transactional
    public void saveGoods(SpuBo spuBo) {

        //1、新增spu

        //补全spu属性
        spuBo.setId(null);
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        //保存
        this.spuMapper.insertSelective(spuBo);

        //2、新增spuDetail
        //得到spuDetail
        SpuDetail spuDetail =spuBo.getSpuDetail();
        //设置ID
        spuDetail.setSpuId(spuBo.getId());
        //保存
        this.spuDetailMapper.insert(spuDetail);

        //3、新增sku

        //得到sku
        for (Sku sku: spuBo.getSkus()) {
            sku.setId(null);
            sku.setSpuId(spuBo.getId());
            sku.setEnable(true);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);

            //4、保存stock 库存
            //初始化库存量对象
            Stock stock = new Stock();
            stock.setStock(sku.getStock());
            stock.setSkuId(sku.getId());
            stock.setSeckillStock(10);
            stock.setSeckillTotal(10);
            this.stockMapper.insertSelective(stock);

        }

    }

    //搜索spudetail
    public SpuDetail querySpuDetailBySpuId(long spuId) {

        SpuDetail spuDetail = this.spuDetailMapper.selectByPrimaryKey(spuId);
        return spuDetail;
    }

    //根据spuId搜索所有sku
    public List<Sku> querySkuBySpuId(Long spuId) {

        Sku sku = new Sku();
        sku.setSpuId(spuId);
        //System.out.println("querySkuBySpuId-----------"+"-----------");
        List<Sku> skus = this.skuMapper.select(sku);
        //System.out.println("querySkuBySpuId-----------"+skus.size());
        if (CollectionUtils.isEmpty(skus))return null;
        //System.out.println("querySkuBySpuId-------------------"+stockMapper);
        skus.forEach(sku1 -> {

            Stock stockDetail = stockMapper.selectByPrimaryKey(sku1.getId());
            if(stockDetail==null){
                sku1.setStock(null);
            }else{

                Integer stock = stockDetail.getStock();

                sku1.setStock(stock);
            }
        });
        return skus;
    }

    //修改上下架
    @Transactional
    public void putGoodsOnOrDownByspuId(boolean saleable,Long spuId) {

        if (saleable){
            saleable=false;
            this.spuMapper.putGoodsOnOrDownByspuId(saleable,spuId);
        }else {
            saleable=true;
            this.spuMapper.putGoodsOnOrDownByspuId(saleable,spuId);
        }
    }


    //更新的商品
    @Transactional
    public void updateGoods(SpuBo spuBo) {

        Sku record = new Sku();
        record.setSpuId(spuBo.getId());
        List<Sku> skus = this.skuMapper.select(record);

        //删除stock
        for (Sku sku: skus){
            this.stockMapper.deleteByPrimaryKey(sku.getId());
        }
        //删除sku
        this.skuMapper.delete(record);

        //3、新增sku
        for (Sku sku: spuBo.getSkus()) {
            sku.setId(null);
            sku.setSpuId(spuBo.getId());
            sku.setEnable(true);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);

            //4、保存stock 库存
            //初始化库存量对象
            Stock stock = new Stock();
            stock.setStock(sku.getStock());
            stock.setSkuId(sku.getId());
            this.stockMapper.insertSelective(stock);

        }

        //3、更新spu
        spuBo.setSaleable(null);
        spuBo.setValid(null);
        spuBo.setCreateTime(null);
        spuBo.setLastUpdateTime(new Date());
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        //4、更新spuDetail
        //得到spuDetail

        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

    }

}
